<script setup lang="ts">
import roomStatus from './components/roomStatus.vue' //状态栏
import roomMessage from './components/roomMessage.vue' //聊天
import roomAction from './components/roomAction.vue' //底部操作栏
import io from 'socket.io-client' //及时通讯
import type { Socket } from 'socket.io-client' //即时通讯类型
import { onMounted, onUnmounted } from 'vue'
import { baseURL } from '@/utils/request'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'

import type { Message, TimeMessages } from '@/types/room'
import { MsgType, OrderType } from '@/enum'
import { ref, nextTick, provide } from 'vue'
import { getConsultOrderDetail } from '@/services/consult'
import type { ConsultOrderItem, Image } from '@/types/consult'
import dayjs from 'dayjs'
import { showToast } from 'vant'

const store = useUserStore()
const route = useRoute()
const list = ref<Message[]>([])
const initMsg = ref(true) //判断是否是第一次加载聊天记录

let socket: Socket

onMounted(() => {
  getOrderDetail()
  socket = io(baseURL, {
    auth: {
      token: `Bearer ${store.user?.token}`
    },
    query: {
      orderId: route.query.orderId
    }
  })

  socket.on('connect', () => {
    console.log('socket连接成功')
  })
  socket.on('disconnect', () => {
    console.log('socket连接关闭')
  })
  socket.on('error', () => {
    console.log('socket发生错误')
  })

  // 首次获取聊天记录
  socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
    const arr: Message[] = []
    data.forEach((item, i) => {
      if (i === 0) time.value = item.createTime //记录每一段消息中最早时间  获取上一段聊天记录要用
      arr.push({
        msgType: MsgType.Notify,
        msg: {
          content: item.createTime
        },
        createTime: item.createTime,
        id: item.createTime
      })
      arr.push(...item.items)
    })

    list.value.unshift(...arr) //往前追加
    loading.value = false
    if (!arr.length) return showToast('没有更多聊天记录啦')

    if (initMsg.value) {
      socket.emit('updateMsgStatus', arr[arr.length - 1].id) //最新消息id 已进入页面就让所有消息改为已读
      // 第一次需要滚到最新消息
      nextTick(() => {
        window.scroll(0, document.body.scrollHeight)
        initMsg.value = false
      })
    }
  })

  // 接收聊天消息
  socket.on('receiveChatMsg', async (event) => {
    socket.emit('updateMsgStatus', event.id) //最新消息id 已进入页面就让所有消息改为已读
    list.value.push(event)
    await nextTick() //等待渲染完成在滚动
    window.scroll(0, document.body.scrollHeight)
  })

  // 监听订单状态变化
  socket.on('statusChange', async () => {
    getOrderDetail()
  })
})
onUnmounted(() => {
  socket.close()
})
// 获取订单详情
const consult = ref<ConsultOrderItem>()
const getOrderDetail = async () => {
  const res = await getConsultOrderDetail(route.query.orderId as string)
  consult.value = res.data
}
provide('consult', consult)

const completeEva = (score: number) => {
  const item = list.value.find((item) => item.msgType === MsgType.CardEvaForm)
  if (item) {
    item.msg.evaluateDoc = { score }
    item.msgType = MsgType.CardEva
  }
}
provide('completeEva', completeEva)

//用户聊天传过来的数据
const sendText = (text: string) => {
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgText,
    msg: {
      content: text
    }
  })
}

//用户上传的图片
const sendImg = (img: Image) => {
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgImage,
    msg: {
      picture: img
    }
  })
}

//上拉加载数据
const loading = ref(false)
const time = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))
const onRefresh = () => {
  // 20是向服务器要多少条数据
  // time.value 要获取最早聊天记录时间
  //consult.value?.id 订单orderId

  socket.emit('getChatMsgList', 20, time.value, consult.value?.id)
}
</script>

<template>
  <div class="room-page" v-if="consult">
    <cp-nav-bar title="医生问诊室" />
    <room-status :status="consult?.status" :countdown="consult?.countdown" />
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <roomMessage v-for="item in list" :key="item.id" :item="item" />
    </van-pull-refresh>
    <room-action
      :disabled="consult?.status !== OrderType.ConsultChat"
      @send-text="sendText"
      @send-img="sendImg"
    />
  </div>
</template>
<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
